#!/usr/bin/python2
#-*- coding: utf-8 -*-

template = open("template.html").read()
from jinja2 import Template
import os
import re
from sys import stdout

system = lambda s: (os.system(s), stdout.write('>%s\n' % s))


DEFAULTIMGSTYLE="colored"
PROJECTNAME='test'
SUBTITLE='sub'
SOURCE='src/content'
WWW='www'
INC='src/inc'
FOOTER='lambdadelta project &copy; 2013'

def render_article(ospath, filetree, workdir):
	content = open(SOURCE+'/'+ospath).readlines()
	title = content.pop(0).strip()
	content = list(map(lambda s: s.strip() + '\n', '\n'.join(content).split('<!--PAGE-->')))
	for i in range(len(content)):
		content[i] = list(map(lambda s: s.strip() + '\n', content[i].split('<!---->')))
 
	def get_subtree(filetree, path):
		category = list(filter(lambda x: x['href'] == '/'+'/'.join(path.split('/')[:1]), filetree))[0]
		if len(path.split('/')) == 1:
			return category
		subcategory = list(filter(lambda x: x['href'] == '/'+'/'.join(path.split('/')[:2]), category['subcategories']))[0]
		if len(path.split('/')) == 2:
			return subcategory
		article = list(filter(lambda x: x['href'] == '/'+'/'.join(path.split('/')[:3]), subcategory['articles']))[0]
		return article

	global PROJECTNAME, SUBTITLE
	context = dict()
	context['projectname'] = PROJECTNAME
	context['subtitle'] = SUBTITLE
	context['footer'] = FOOTER
	context['categories'] = filetree
	category = get_subtree(filetree, ospath.split('/')[0])
	category['active'] = True
	context['subcategories'] = category['subcategories']
	subcategory = get_subtree(filetree, '/'.join(ospath.split('/')[:2]))
	context['cursubcategory'] = subcategory['caption']
	article = get_subtree(filetree, '/'.join(ospath.split('/')[:3]))
	article['active'] = True

	def calc_prev_art(osdir, filetree):
		cat, subcat, art = osdir.split('/')
		ind = 0
		while get_subtree(filetree, cat + '/' + subcat)['articles'][ind]['href'] != '/' + cat + '/' + subcat + '/' + art:
			ind += 1
		if ind != 0:
			return get_subtree(filetree, cat + '/' + subcat)['articles'][ind-1]['href']
		else:
			return None

	def calc_next_art(osdir, filetree):
		cat, subcat, art = osdir.split('/')
		ind = 0
		while get_subtree(filetree, cat + '/' + subcat)['articles'][ind]['href'] != '/' + cat + '/' + subcat + '/' + art:
			ind += 1
		if ind != len(get_subtree(filetree, cat + '/' + subcat)['articles']) - 1:
			return get_subtree(filetree, cat + '/' + subcat)['articles'][ind+1]['href']
		else:
			return None

	context['pagination'] = {
		'prevart': calc_prev_art(ospath, filetree),
		'nextart': calc_next_art(ospath, filetree),
		'pages': list(),
	}

	for i in range(len(content)):
		context['pagination']['pages'].append({
			'href': '/' + ospath + '/' + (str(i+1) if i else 'index') + '.html',
			'caption': i+1,
			'active': False,
		})

	context['page'] = dict()
	context['page']['caption'] = article['caption']

	for foo in range(len(content)):
		if foo:
			context['pagination']['pages'][foo-1]['active'] = False
		context['pagination']['pages'][foo]['active'] = True
		if foo:
			context['pagination']['prev'] = context['pagination']['pages'][foo-1]['href']
		else:
			context['pagination']['prev'] = ''
		if foo+1 != len(content):
			context['pagination']['next'] = context['pagination']['pages'][foo+1]['href']
		else:
			context['pagination']['next'] = ''

		context['page']['paragraphs'] = []

		for bar in content[foo]:
			bar = bar.strip()
			boo = ''
			bee = DEFAULTIMGSTYLE
			if not bar:
				continue
			if bar[0] == '<':
				boo = bar[1:bar.index('>')]
				bar = bar[bar.index('>')+1:]
				if '@' in boo:
					boo, bee = boo.split('@')

			context['page']['paragraphs'].append({
				'content': bar,
				'media': boo,
				'imgstyle': bee,
			})

		open(workdir + '/' + context['pagination']['pages'][foo]['href'], 'w').write(Template(open('template.html').read()).render(**context))
	category['active'] = False
	article['active'] = False
	stdout.write('>%s\n' % (workdir + '/' + context['pagination']['pages'][foo]['href']))


def build_tree():
	context = dict()
	context['categories'] = list()
	order = list(filter(None, map(str.strip, open(SOURCE+ '/' +'info').readlines())))
	global PROJECTNAME, SUBTITLE, FOOTER
	PROJECTNAME = order.pop(0)
	SUBTITLE = order.pop(0)
	try:
		FOOTER = open(PREFIX + '/' + 'footer').read()
	except:
		pass
	for cat in order:
		catinfo = list(filter(None, map(str.strip, open(SOURCE+'/'+cat + '/info').readlines())))
		category = dict()
		category['caption'] = catinfo.pop(0)
		category['href'] = '/' + cat
		category['subcategories'] = list()
		for subcat in catinfo:
			subcatinfo = list(filter(None, map(str.strip, open(SOURCE + '/' + cat + '/' + subcat + '/info').readlines())))
			subcategory = dict()
			subcategory['caption'] = subcatinfo.pop(0)
			subcategory['href'] = '/' + cat + '/' + subcat
			subcategory['articles'] = list()
			for art in subcatinfo:
				article = {
						'href': '/' + cat + '/' + subcat + '/' + art,
						'caption': open(SOURCE + '/' + cat + '/' + subcat + '/' + art).readline().strip(),
				}
				subcategory['articles'].append(article)
			category['subcategories'].append(subcategory)
		context['categories'].append(category)
	return context

def render_site(treelist):
	context = dict()
	context['categories'] = list()
	order = list(filter(None, map(str.strip, open(SOURCE+ '/' +'info').readlines())))
	order.pop(0), order.pop(0)
	system('rm -r %s/*' % WWW)
	fcat = None
	for cat in order:
		fcat = fcat or cat
		catinfo = list(filter(None, map(str.strip, open(SOURCE+'/'+cat + '/info').readlines())))
		system('mkdir %s/%s' % (WWW, cat))
		catinfo.pop(0)
		fsubcat = None
		for subcat in catinfo:
			fsubcat = fsubcat or subcat
			subcatinfo = list(filter(None, map(str.strip, open(SOURCE + '/' + cat + '/' + subcat + '/info').readlines())))
			system('mkdir %s/%s/%s' % (WWW, cat, subcat))
			subcatinfo.pop(0)
			fart = None
			for art in subcatinfo:
				fart = fart or art
				system('mkdir %s/%s/%s/%s' % (WWW, cat, subcat, art))
				render_article(cat + '/' + subcat + '/' + art, treelist['categories'], WWW)
			system('cp %s/%s/%s/%s/index.html %s/%s/%s/index.html' % (WWW, cat, subcat, fart, WWW, cat, subcat))
		system('cp %s/%s/%s/index.html %s/%s/index.html' % (WWW, cat, fsubcat, WWW, cat))
	system('cp %s/%s/index.html %s/index.html' % (WWW, fcat, WWW))
	system('cp -r %s/* %s/' % (INC, WWW))
	return context

treelist = build_tree()

system('rm %s.dump' % WWW)
system('cp -r %s %s.dump' % (WWW, WWW))
try:
	render_site(treelist)
except:
	print('FAILED')
	system('mv %s.dump %s' % (WWW, WWW))
	exit(1)